package com.jdy.haoduoai.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.activity.BaseActivity;
import com.jdy.haoduoai.activity.PrivatechannelActivity;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.PrivateChannelMenuItemVo;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.ycsj.goldmedalnewconcept.R;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 
 * @author lzq
 * 
 */
@SuppressLint("InflateParams")
public class PrivateChannelRefreshAdapter extends BaseAdapter implements
    OnItemClickListener, OnClickListener {

  private BaseActivity mContext;
  private PrivatechannelActivity pa;
  private ArrayList<PrivateChannelMenuItemVo> mList;
  private LayoutInflater mInflater;
  private PrivateChannelMenuItemAdapter adapter;
  DisplayImageOptions options;
  DisplayMetrics dm;
  private Handler handler;
  private float NUM = (float) 3.5; // 每行显示个数
  private float LIEWIDTH;// 每列宽度

  public PrivateChannelRefreshAdapter(BaseActivity context,
                                      ArrayList<PrivateChannelMenuItemVo> list, Handler hd) {
    this.mContext = context;
    pa = (PrivatechannelActivity) context;
    this.mList = list;
    handler = hd;
    mInflater = LayoutInflater.from(mContext);
    getScreenDen();
    LIEWIDTH = dm.widthPixels / NUM;

    // 用 displayImage 加载图片 的 配置参数
    options = new DisplayImageOptions.Builder()
        .showImageOnFail(R.drawable.default_img_listitem) // 下载 失败 显示的 图片
        .cacheInMemory(true) // 缓存
        .bitmapConfig(Bitmap.Config.RGB_565) // 图片格式
        .build();
    // 创建默认的ImageLoader配置参数
    ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
        mContext).writeDebugLogs() // 打印 log 信息
        .build();
    ImageLoader.getInstance().init(configuration);
  }

  private void getScreenDen() {
    dm = new DisplayMetrics();
    mContext.getWindowManager().getDefaultDisplay().getMetrics(dm);
  }

  @Override
  public int getCount() {
    return mList.size();
  }

  @Override
  public Object getItem(int position) {
    return mList.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    PrivateChannelMenuItemVo menuItemVo = mList.get(position);
    ViewHolder holder;
    if (convertView == null) {
      holder = new ViewHolder();
      convertView = mInflater.inflate(R.layout.privatechannelitem, null);
      holder.typeicon = (ImageView) convertView.findViewById(R.id.typeicon);
      holder.ItemText = (TextView) convertView.findViewById(R.id.titleText);
      holder.rechange = (ImageButton) convertView.findViewById(R.id.rechange);
      holder.gridView = (GridView) convertView.findViewById(R.id.gridview);
      holder.pushbtn = (ImageButton) convertView.findViewById(R.id.pushbtn);
      convertView.setTag(holder);
    } else {
      holder = (ViewHolder) convertView.getTag();
    }

    holder.ItemText.setText(menuItemVo.name);
    switch (menuItemVo.name) {
    case "吃饭":
      holder.ItemText.setTextColor(Color.parseColor("#f78597"));
      break;
    case "学习":
      holder.ItemText.setTextColor(Color.parseColor("#4fbdeb"));
      break;
    case "洗漱":
      holder.ItemText.setTextColor(Color.parseColor("#10b55a"));
      break;
    case "情绪":
      holder.ItemText.setTextColor(Color.parseColor("#ff8a00"));
      break;
    case "社交":
      holder.ItemText.setTextColor(Color.parseColor("#f25c5c"));
      break;
    case "睡眠":
      holder.ItemText.setTextColor(Color.parseColor("#1d4aa2"));
      break;
    case "性格":
      holder.ItemText.setTextColor(Color.parseColor("#a675cc"));
      break;
    default:
      break;
    }
    ImageLoader.getInstance().displayImage(menuItemVo.imgurl, holder.typeicon,
        options);

    adapter = new PrivateChannelMenuItemAdapter(mContext, menuItemVo.list);
    holder.gridView.setAdapter(adapter);
    LayoutParams params = new LayoutParams(
        (int) (adapter.getCount() * LIEWIDTH), LayoutParams.WRAP_CONTENT);
    holder.gridView.setLayoutParams(params);
    holder.gridView.setColumnWidth((int) (dm.widthPixels / 3.5));
    holder.gridView.setStretchMode(GridView.NO_STRETCH);
    holder.gridView.setNumColumns(menuItemVo.list.size());
    setListener(holder, menuItemVo);
    return convertView;
  }

  private void setListener(ViewHolder holder, PrivateChannelMenuItemVo to) {
    holder.gridView.setTag(to);
    holder.gridView.setOnItemClickListener(this);
    holder.pushbtn.setTag(to);
    holder.pushbtn.setOnClickListener(this);
    holder.rechange.setTag(to);
    holder.rechange.setOnClickListener(this);
  }

  private static class ViewHolder {
    public ImageView typeicon;
    public TextView ItemText;
    private ImageButton rechange;
    public GridView gridView;
    public ImageButton pushbtn;
  }

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position,
      long id) {
    PrivateChannelMenuItemVo item = (PrivateChannelMenuItemVo) parent.getTag();
    Toast.makeText(mContext, item.list.get(position).album_name,
        Toast.LENGTH_SHORT).show();

    playvideo(item.list.get(position).id, "cartoon");
  }

  private boolean isDoubleClick = false;

  private OnChangeCallback mOnChangeCallback;

  public OnChangeCallback getOnChangeCallback() {
    return mOnChangeCallback;
  }

  public void setOnChangeCallback(OnChangeCallback mOnChangeCallback) {
    this.mOnChangeCallback = mOnChangeCallback;
  }

  public interface OnChangeCallback {
    public void onChangeClick(String key); // key是"吃饭、学习、睡觉等某一个"
  }

  @Override
  public void onClick(View v) {
    PrivateChannelMenuItemVo item = (PrivateChannelMenuItemVo) v.getTag();
    switch (v.getId()) {
    case R.id.rechange:
      Toast.makeText(mContext, "换一批", Toast.LENGTH_SHORT).show();

      if (mOnChangeCallback != null) {
        mOnChangeCallback.onChangeClick(item.name);
      }
      break;
    case R.id.pushbtn:

      if (!isDoubleClick) {
        isDoubleClick = true;
        Toast
            .makeText(mContext, item.name + item.id + "推送", Toast.LENGTH_SHORT)
            .show();

        if (handler != null) {
          handler.postDelayed(new Runnable() {
            @Override
            public void run() {
              isDoubleClick = false;
            }
          }, 2000);
        }
      } else {
        Toast.makeText(mContext, "该内容已经推送至小小班", Toast.LENGTH_SHORT).show();
      }

      break;
    default:
      break;
    }
  }

  private void playvideo(final int sid, final String status) {
    new CustomAsyncTask(mContext, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          DateUtils.showToast(mContext, "已推送到设备播放");
//          if (LeConfig.isDeviceConnect) {
//            DateUtils.showToast(mContext, "已推送到设备播放");
//          } else {
//            DateUtils.showToast(mContext, "未连接到设备，请检查设备联网情况！");
//          }
        } else {
          LeConfig.isDeviceConnect = false;
          DateUtils.showToast(mContext, "设备不在线");
        }
        // if (result.isSuccess()) {
        // // if (("cartoon").equals(status) || ("continue").equals(status)) {
        // // toastShow("推送成功");
        // // isPlay = true;
        // // // playbutton.setBackgroundResource(R.drawable.pause_icon);
        // // } else if (("pause").equals(status)) {
        // // toastShow("暂停播放");
        // // isPlay = false;
        // // // playbutton.setBackgroundResource(R.drawable.ico_play);
        // // } else {
        // // toastShow(result.data);
        // // }
        // } else {
        // mContext.toastShow(result.data);
        // }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        HashMap<String, Object> param_ = new HashMap<String, Object>();

        int uid = -1, volume = -1, minutes = -1;
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();

        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
        param_.put(HttpUtils.TAG_OPERATION_I, "cartoon");
        param_.put(HttpUtils.TAG_TYPE_I, "cartoon");
       // param_.put("mode", "im");

        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }

        param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

}
